#include "display/ThreadDisplay.hpp"

using namespace std;

/**
 * Init the window
 */
ThreadDisplay::ThreadDisplay() : m_app(0), m_displayable(0), m_NewDisplayable(0)
{
    m_app = new sf::RenderWindow;
}

ThreadDisplay::~ThreadDisplay()
{
    delete m_app;
    if(this->m_displayable != 0)
    {
    	delete this->m_displayable;
    }
}
/**
 * Change the displayable (the thing to display)
 */
void ThreadDisplay::setDisplayable(Displayable* displayable)
{
    //Debug::printTrace(Debug::information, "display/ThreadDisplay.setDisplayable", "Change the displayable");
    this->m_NewDisplayable = displayable;
}
/**
 * Do the transition betwen the old and the new displayable (to don't break the screen)
 */
void ThreadDisplay::ChangeDisplayable()
{
	//Debug::printTrace(Debug::information, "display/ThreadDisplay.ChangeDisplayable", "Check change");

    if(this->m_NewDisplayable != this->m_displayable)
    {
    	//Debug::printTrace(Debug::information, "display/ThreadDisplay.ChangeDisplayable", "Changing");

    	delete this->m_displayable;
    	this->m_displayable = this->m_NewDisplayable;
    }
}
/**
 * Display framerate on the screen with default police
 */
void ThreadDisplay::DisplayFramerate()
{
    sf::String text;

    text.SetText(Text::float2string(1.f / m_app->GetFrameTime()));
    text.SetColor(sf::Color::White);

    m_app->Draw(text);
}
/**
 * loop to draw a displayable Object
 */
void ThreadDisplay::Run()
{
    // little hack
    m_app->Create(sf::VideoMode(DefaultValue::MAP_SIZE_X , DefaultValue::MAP_SIZE_Y, 32), "Perillous garden");

	m_app->SetFramerateLimit(40);
    m_app->UseVerticalSync(true);

    while (m_app->IsOpened())
    {
        this->ChangeDisplayable();

        // Process events
        sf::Event event;
        while (m_app->GetEvent(event))
        {
            // Close window : exit
            if (event.Type == sf::Event::Closed)
                m_app->Close();

            this->m_displayable->DoEvent(event);
        }

        this->m_displayable->DoRealTimeEvent(m_app->GetInput());

        m_app->Clear();
        this->m_displayable->draw(m_app);

        DisplayFramerate();

        m_app->Display();
    }
}
